import React, { PureComponent } from 'react';
import {
  Row,
  Col,
  Input,
  Button,
  Form,
  DatePicker,
  Checkbox,
  Icon,
} from 'antd';
import { UpOutlined, DownOutlined } from '@ant-design/icons';
import classnames from 'classnames';
import moment from 'moment';
import SelectCustom from '../../input/selectCustom';
import { inputTrim } from '../../../utils/utils';
import EventsBus from '../../../utils/events';
import { getList } from '../util';
import styles from './filter.less';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const formItemLayoutDate = {
  labelCol: { span: 6 },
  wrapperCol: { span: 17 },
  style: {
    position: 'relative',
    left: '-12.8%',
    width: '115%',
  },
};
// const { MonthPicker } = DatePicker;
class Filter extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      open: false,
      columnsFilter: getList(props.columnsFilter),
    };
    this.formRef = React.createRef();
  }

  componentDidMount() {
    const { pathname } = window.location;
    EventsBus.addListener(`${pathname}=refresh`, () => {
      const { props } = this;
      this.setState({
        columnsFilter: getList(props.columnsFilter),
      });
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    /* ! 千万不要每次都传新的，会卡死的   用useMome  */
    /*
     * listArr 这个数组是不确定什么时候从后台拉取成功了，所以，这就是该行代码的意义
     * */
    if (nextProps.columnsFilter !== this.props.columnsFilter) {
      this.setState({
        columnsFilter: getList(nextProps.columnsFilter),
      });
    }
  }

  onOpenClick = () => {
    this.setState((preState) => {
      return {
        open: !preState.open,
      };
    });
  };

  onAdvancedSearchSubmit = () => {
    const { onSearch } = this.props;
    const values = this.getValues();
    onSearch(values);
  };

  onAdvancedSearchReset = () => {
    const { onReset } = this.props;
    this.formRef.current.resetFields();
    // const values = this.getValues();
    const parms = {};
    onReset && onReset(parms);
  };

  // 该过滤是控制展开收起
  getShowColumnsFilter = () => {
    const { open, columnsFilter } = this.state;
    const numObj = this.num().clear();
    const max = 18; // 计数到18即为一行
    const columns = columnsFilter.filter((i) => i.show);
    if (open) {
      return columns;
    } else {
      const list = []; // 待显示的列表
      for (let i = 0; i < columns.length; i += 1) {
        numObj.add(columns[i]);
        if (columns[i].show && numObj.getNum() <= max) {
          list.push(columns[i]);
        }
      }
      return list;
    }
  };

  // 刷新
  reFlush = () => {
    const { columnsFilter } = this.props;
    this.setState({
      columnsFilter: getList(columnsFilter),
    });
  };

  trim = (e) => {
    const value = String(e.target.value).trim();
    return value;
  };

  // 渲染lable
  labelRender = (item) => {
    if (item.labelRender) {
      // Render优先
      return item.labelRender;
    }
    const text = item.label;
    if (text && text.length > 5) {
      // 让他小一点
      return <span style={{ fontSize: '10px' }}>{text}</span>;
    }
    return text;
  };

  // 一个计数器
  num = () => {
    let mas = 0;
    return {
      clear() {
        mas = 0;
        return this;
      },
      add(item) {
        if (item.inputType === 'dataRange') {
          mas += 12;
        } else if (item.inputType === 'checkBox') {
          mas += 3;
        } else {
          mas += 6;
        }
        return mas;
      },
      getNum() {
        return mas;
      },
    };
  };

  // 获取所有数据
  getValues = () => {
    // const state = this.state;
    const { columnsFilter } = this.state;
    const { submitPreMiddleware, defaultConditon = {} } = this.props;
    let values = this.formRef.current.getFieldsValue();
    const valuesKey = Object.keys(values);
    for (let i = 0; i < valuesKey.length; i += 1) {
      if (values[valuesKey[i]] && values[valuesKey[i]].valueOf) {
        // 日期转化为时间戳
        values[valuesKey[i]] = values[valuesKey[i]].valueOf();
      }
    }
    // 日期输入反了，自动给他调过开
    columnsFilter.forEach((i) => {
      if (
        i.inputType === 'dataRange' &&
        i.value.length &&
        i.value.length === 2
      ) {
        // 开始调整日期
        if (
          values[i.value[0]] &&
          values[i.value[1]] &&
          Number(values[i.value[0]]) > Number(values[i.value[1]])
        ) {
          const a = values[i.value[0]];
          values[i.value[0]] = values[i.value[1]];
          values[i.value[1]] = a;
          this.formRef.current.setFieldsValue({
            [i.value[0]]: moment(new Date(values[i.value[0]])),
            [i.value[1]]: moment(new Date(values[i.value[1]])),
          });
        }
      }
    });
    if (submitPreMiddleware) {
      // 暴露一个外部可以处理参数的接口
      values = submitPreMiddleware(values);
    }
    return { ...defaultConditon, ...values };
  };

  render() {
    const props = this.props;
    const { open, columnsFilter } = this.state;
    const { defaultConditon = {} } = this.props;
    const list = this.getShowColumnsFilter();
    const numObj = this.num().clear();

    const showList = columnsFilter.filter((item) => item.show);
    return (
      <div className={classnames('filter', styles.filter, styles.content)}>
        <div
          style={{
            display: 'none',
            position: 'absolute',
            top: '-10px',
            right: '0px',
            cursor: 'pointer',
            ...props.iconStyle,
          }}
        >
          <Icon onClick={this.onClickMenu} type="setting" />
        </div>
        <Form ref={this.formRef}>
          <div className={styles.dashed}>
            <Row gutter={24}>
              {list.map((i, index) => {
                numObj.add(i);
                let content = false;
                if (i.render) {
                  content = (
                    <Col
                      // style={{ height: '48px' }}
                      span={i.inputType === 'dataRange' ? 12 : 6}
                      key={i.label}
                    >
                      {i.render(
                        FormItem,
                        i.inputType === 'dataRange'
                          ? formItemLayoutDate
                          : formItemLayout,
                        defaultConditon,
                      )}
                    </Col>
                  );
                } else if (i.inputType === 'code') {
                  content = (
                    <Col span={6} key={i.label}>
                      <FormItem
                        {...formItemLayout}
                        label={this.labelRender(i)}
                        name={i.value}
                        initialValue={defaultConditon[i.value]}
                        getValueFromEvent={inputContract}
                      >
                        <Input placeholder="请输入" />
                      </FormItem>
                    </Col>
                  );
                } else if (i.inputType === 'text') {
                  content = (
                    <Col span={6} key={i.label}>
                      <FormItem
                        {...formItemLayout}
                        label={this.labelRender(i)}
                        name={i.value}
                        initialValue={defaultConditon[i.value]}
                        getValueFromEvent={inputTrim}
                      >
                        <Input placeholder="请输入" />
                      </FormItem>
                    </Col>
                  );
                } else if (
                  i.inputType &&
                  i.inputType.split(',')[0] === 'select'
                ) {
                  content = (
                    <Col span={6} key={i.label}>
                      <FormItem
                        {...formItemLayout}
                        label={this.labelRender(i)}
                        name={i.value}
                        initialValue={defaultConditon[i.value]}
                      >
                        <SelectCustom
                          optionList={i.listArr || []}
                          keyValue={i.keyValue || ['name', 'id']}
                          mode={i.inputType.split(',')[1] || ''}
                          // extraObject={{
                          //   id: currentItem.cooperativePartnerId,
                          //   name: currentItem.cooperativePartnerName,
                          // }}
                        />
                      </FormItem>
                    </Col>
                  );
                } /* else if (i.inputType === 'cascaderProduct') {
                  content = (
                    <Col span={6} key={i.label}>
                      <FormItem {...formItemLayout} label={this.labelRender(i)}>
                        {getFieldDecorator(i.value, {
                          initialValue: defaultConditon[i.value],
                        })(
                          <ProductCategoryCascader
                            productList={i.listArr || props.preThis.props[props.type][i.listName]}
                          />
                        )}
                      </FormItem>
                    </Col>
                  );
                } */ else if (
                  i.inputType === 'dataRange'
                ) {
                  content = (
                    <Col span={12} key={i.label} style={{ overflow: 'hidden' }}>
                      <FormItem
                        {...formItemLayoutDate}
                        label={this.labelRender(i)}
                      >
                        <Row>
                          <Col span={11}>
                            <FormItem
                              name={i.value[0]}
                              initialValue={
                                defaultConditon[i.value[0]]
                                  ? moment(
                                      new Date(defaultConditon[i.value[0]]),
                                    )
                                  : undefined
                              }
                            >
                              <DatePicker
                                style={{ width: '100%' }}
                                format="YYYY/MM/DD"
                              />
                            </FormItem>
                          </Col>
                          <Col
                            span={2}
                            style={{
                              textAlign: 'center',
                              display: 'flex',
                              justifyContent: 'center',
                              alignItems: 'center',
                            }}
                          >
                            ~
                          </Col>
                          <Col span={11}>
                            <FormItem
                              name={i.value[1]}
                              initialValue={
                                defaultConditon[i.value[1]]
                                  ? moment(
                                      new Date(defaultConditon[i.value[1]]),
                                    )
                                  : undefined
                              }
                            >
                              <DatePicker
                                style={{ width: '100%' }}
                                format="YYYY/MM/DD"
                              />
                            </FormItem>
                          </Col>
                        </Row>
                      </FormItem>
                    </Col>
                  );
                } else if (i.inputType === 'checkBox') {
                  content = (
                    <Col
                      span={3}
                      style={{
                        paddingLeft: 0,
                        paddingRight: 0,
                        position: 'relative',
                        left: '3%',
                      }}
                    >
                      <FormItem
                        valuePropName="checked"
                        name={i.value}
                        initialValue={defaultConditon[i.value]}
                      >
                        <Checkbox>{i.label}</Checkbox>
                      </FormItem>
                    </Col>
                  );
                }
                if (
                  numObj.getNum() === 24 ||
                  numObj.getNum() === 21 ||
                  (numObj.getNum() === 18 &&
                    list[index + 1] &&
                    list[index + 1].inputType === 'dataRange')
                ) {
                  numObj.clear();
                  return (
                    <>
                      {content}
                      <Col span={24} />
                    </>
                  );
                }
                return content;
              })}
              <Col
                className={styles.textRight}
                style={{
                  float: 'right',
                  marginTop: '-1px',
                  marginLeft: 'auto',
                  marginBottom: 12,
                }}
              >
                <Button
                  style={{ marginRight: '8px' }}
                  type="primary"
                  onClick={this.onAdvancedSearchSubmit}
                  htmlType="submit"
                >
                  查询
                </Button>
                <Button onClick={this.onAdvancedSearchReset}>重置</Button>
                <a
                  style={{
                    marginLeft: '8px',
                    display: showList.length <= 2 ? 'none' : '',
                  }}
                  onClick={this.onOpenClick}
                >
                  {open ? '收起' : '展开'}
                  {open ? (
                    <UpOutlined style={{ marginLeft: '4px' }} />
                  ) : (
                    <DownOutlined style={{ marginLeft: '4px' }} />
                  )}
                </a>
              </Col>
            </Row>
          </div>
        </Form>
      </div>
    );
  }
}

export default Filter;
